package cn.portx.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class PinyinFirstletterUtils {

	/**
	 * 获取汉语拼音首字母
	 * 
	 * @param chinese
	 * @return
	 * @throws Exception
	 */
	public static String getPfl(String chinese) throws Exception {
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
		chinese += " ";
		String separator = ",";
		boolean retain = false;
		String pinyin = StringUtils.trim(PinyinHelper.toHanYuPinyinString(chinese, defaultFormat, separator, retain));
		if (StringUtils.endsWith(pinyin, separator)) {
			pinyin = StringUtils.substringBeforeLast(pinyin, separator);
		}
		List<String> list = new ArrayList<String>();
		for (String s : StringUtils.split(pinyin, separator)) {
			list.add(String.valueOf(s.charAt(0)));
		}
		return StringUtils.join(list, "");
	}

}
